package com.example.websocketserver.service.impl;

import com.alibaba.fastjson.JSON;
import com.example.websocketserver.pojo.EurekaMessage;
import com.example.websocketserver.service.EurekaService;
import com.example.websocketserver.util.InstanceUtil;
import com.example.websocketserver.util.Result;
import com.example.websocketserver.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class EurekaServiceImpl implements EurekaService {
    @Autowired
    private DiscoveryClient discoveryClient;


    @Override
    public List<EurekaMessage> getServicesList() {
        List<EurekaMessage> list = new ArrayList<>();
        //获取服务名称
        List<String> serviceNames = discoveryClient.getServices();
        EurekaMessage eurekaMessage = null;
        for (String serviceName : serviceNames) {
            eurekaMessage = new EurekaMessage();
            //获取服务中的实例列表
            List<ServiceInstance> serviceInstances = discoveryClient.getInstances(serviceName);
            Map map = JSON.parseObject(JSON.toJSONString(serviceInstances.get(0)), Map.class);
            System.out.println(map);
            eurekaMessage.setServiceId((String)map.get("serviceId"));
            eurekaMessage.setHost((String)map.get("host"));
            eurekaMessage.setPort((Integer)map.get("port"));
            Map map1 = JSON.parseObject(JSON.toJSONString(map.get("instanceInfo")), Map.class);
            eurekaMessage.setStatus((String)map1.get("status"));
            list.add(eurekaMessage);
        }
        return list;
    }

    @Override
    public Result deleteEurekaApps(String serviceId) {
        InstanceUtil.deleteEurekaApp();
        return ResultUtil.success();
    }



}
